package cn.zmwh.im.server.modules.message.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.zmwh.im.common.pojo.dto.IMUserInfo;
import cn.zmwh.im.common.pojo.dto.transfer.Message;
import cn.zmwh.im.server.config.HintManager;
import cn.zmwh.im.server.constant.BsKImConstant;
import cn.zmwh.im.server.modules.message.mapper.ImMessageMapper;
import cn.zmwh.im.server.modules.message.pojo.entity.ImGroupMessage;
import cn.zmwh.im.server.modules.message.pojo.entity.ImMessage;
import cn.zmwh.im.server.modules.message.pojo.request.HistoryRequest;
import cn.zmwh.im.server.modules.ums.pojo.entity.ImUser;
import cn.zmwh.im.server.modules.ums.service.ImUserService;
import cn.zmwh.im.server.netty.ReissueMessageService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 群消息 服务实现类
 * </p>
 *
 * @author dmzmwh
 * @since 2025-06-19
 */
@Slf4j
@Service
public class ImMessageService extends ServiceImpl<ImMessageMapper, ImMessage> {

    @Autowired
    private ReissueMessageService reissueMessageService;
    @Autowired
    private ImUserService imUserService;

    public void history(HistoryRequest request, IMUserInfo receiver) {
        String messageId = request.getMessageId();
        if (StrUtil.isBlank(messageId)) {
            return;
        }
        Long uid = request.getUid();

        ImUser byId = imUserService.getById(uid);
        try (HintManager hintManager = HintManager.getInstance()) {
            Integer messageDb = byId.getMessageDb();
            Integer messageTable = byId.getMessageTable();
            hintManager.addDbValue(BsKImConstant.DbName.IM_MESSAGE, messageDb);
            hintManager.addTableValue(messageTable);
            Date historyTime = DateUtil.offsetMonth(new Date(), -2);
            if (StrUtil.isBlank(messageId)){
                ImMessage one = getOne(Wrappers.<ImMessage>lambdaQuery()
                        .eq(ImMessage::getUid, uid)
                        .eq(ImMessage::getMessageId, messageId));
                if (one != null && one.getSendTime().after(historyTime)) {
                    historyTime = one.getSendTime();
                }
            }
            List<ImMessage> list = list(Wrappers.<ImMessage>lambdaQuery()
                    .eq(ImMessage::getUid, uid)
                    .gt(ImMessage::getSendTime, historyTime)
                    .orderByAsc(Message::getSendTime));

            reissueMessageService.messageSendHistory(list, receiver);
        }
    }
}
